package com.qf.electronic.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.electronic.common.R;
import com.qf.electronic.common.ResponseStatus;
import com.qf.electronic.pojo.Defect;
import com.qf.electronic.service.IDefectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/defect")
public class DefectController {

    @Autowired
    private IDefectService defectService;

    @PostMapping
    public R<Boolean> addDefect(@Valid @RequestBody Defect defect, BindingResult result){
        if(result.hasFieldErrors()){
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        return R.ok(defectService.save(defect));
    }

    @PutMapping
    public R<Boolean> updateDefect(@Valid @RequestBody Defect defect, BindingResult result){
        if(result.hasFieldErrors()){
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        return R.ok(defectService.updateById(defect));
    }

    @DeleteMapping("/{id}")
    public R<Boolean> deleteDefect(@PathVariable("id") int id){
        return R.ok(defectService.removeById(id));
    }

    @GetMapping("/{type}")
    public R<List<Defect>> searchDefects(@PathVariable("type") String type){
        QueryWrapper<Defect> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        return R.ok(defectService.list(wrapper));
    }
}

